#include <dirent.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fstream>

#include "opencv2/opencv.hpp"
#include "HandDetector.h"

using namespace cv;
using namespace std;

int main(int args, char **argv)
{
    int *bbox = new int[4];
    const string img_load_base_color = "/home/yjy/dataset/palmprint_dectection/palmprint/";
    const string img_load_base_gray = "/home/yjy/dataset/palmprint_dectection/palmvein/";
    const string bbox_save_base = "/home/yjy/dataset/palmprint_dectection/output/";
    string file_name_color;
    string file_name_gray;
    int length, flag;
    Mat gray_img;
    HandDetector *hd;
    dirent *filename;
    DIR *dir = opendir(img_load_base_color.c_str());
    ofstream txt(bbox_save_base + "bbox.txt");
    char *buff = new char[100];

    while ((filename = readdir(dir)) != NULL)
    {
        if (strcmp(filename->d_name, ".") == 0 ||
            strcmp(filename->d_name, "..") == 0)
            continue;

        file_name_color = filename->d_name;
        length = file_name_color.length();
        file_name_gray = file_name_color.substr(0, length - 11);

        //detect & return bbox
        ImageReader ir_color(img_load_base_color + file_name_color);
        ImageReader ir_gray(img_load_base_gray + file_name_gray);
        hd = new HandDetector(ir_gray.binary(), ir_color);
        hd->detect();
        flag = hd->getDetectedBox(bbox);
        if (flag == 0)
        {
            buff[0] = 0;
            buff[1] = 0;
            buff[2] = 0;
            buff[3] = 0;
        }

        /*
        gray_img = cv::Mat::zeros(ir_gray.getImg().rows, ir_gray.getImg().cols, ir_gray.getImg().type());
        cv::rectangle(gray_img, cv::Point2d(bbox[0], bbox[2]), cv::Point2d(bbox[1], bbox[3]), cv::Scalar(1), cv::FILLED, 8, 0);
        cv::rectangle(gray_img, cv::Point2d(bbox[0], bbox[2]), cv::Point2d(bbox[1], bbox[3]), cv::Scalar(255), 1, 8, 0);
        */

        gray_img = hd->getSegmentation();

        //save mask
        cv::imwrite(bbox_save_base + file_name_color, gray_img);
        gray_img.release();

        //write bbox to txt
        sprintf(buff, "%s %d %d %d %d\n", file_name_color.c_str(), bbox[0], bbox[1], bbox[2], bbox[3]);
        txt << buff;

        delete hd;
    }

    txt.close();
    delete buff;
    delete filename;
    delete bbox;

    return 0;
}
